package com.liaojp.sccp.interceptor;

import com.liaojp.sccp.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class MyInterceptor implements HandlerInterceptor {
    private final JwtUtils jwtUtils;

    public MyInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("请求路径：{}", request.getRequestURI());
        if (request.getHeader("token") == null){
            log.info("token为空");
            response.setStatus(401);
            return false;
        }
        if (!jwtUtils.validateToken(request.getHeader("token"))){
            log.info("token验证失败");
            response.setStatus(401);
            return false;
        }
        if (jwtUtils.isExpired(request.getHeader("token"))){
            log.info("token已过期");
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
